package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.LoginMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.LoginService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.EmployeeLoginVO;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private LoginMapper loginMapper;

    @Autowired
    private WeChatProperties properties;

    @Autowired
    private JwtProperties jwtProperties;

    private User user;

    @Override
    public UserLoginVO login(UserLoginDTO loginDTO) {

        Map<String, String> hm = new HashMap<>();
        hm.put("appid", properties.getAppid());
        hm.put("secret", properties.getSecret());
        hm.put("js_code",loginDTO.getCode());
        hm.put("grant_type", "authorization_code");
        String result = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", hm);
        JSONObject jsonObject = JSON.parseObject(result);

        String open_id = jsonObject.get("openid").toString();

        if (open_id == null||open_id.isEmpty()){
            throw new LoginFailedException(MessageConstant.USER_NOT_LOGIN);
        }
         user = loginMapper.selectByOpenId(open_id);

        if (user == null){
            user = User.builder()
                    .openid(open_id)
                    .name(UUID.randomUUID().toString().replace("-", "").substring(0, 5))
                    .createTime(LocalDateTime.now())
                    .build();
            loginMapper.addByOpenId(user);
        }

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);
        return UserLoginVO.builder().id(user.getId()).openid(open_id).token(token).build();
    }
}
